<!-- 添加视频 -->
<!-- 添加视频 -->
<template>
  <div>
    <el-dialog v-model="dialogVisible" width="400" :title="title" alignCenter draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
      <el-form ref="elFormRef" :model="formData" :rules="rules" labelWidth="80px" scrollToError statusIcon>
        <el-form-item label="剧集名称" prop="episodeTitle">
          <el-input v-model="formData.episodeTitle" maxlength="12" placeholder="请输入标签名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="剧集视频" required prop="episodeUrl">
          <rest-upload-qn
            v-model="video"
            :folder="`drama/${formData.dramaId || ''}/episode`"
            :posterFolder="`drama/${formData.dramaId || ''}/cover`"
            :customKeys="{ bindFileUrlKey: 'episodeUrl', bindPosterUrlKey: 'frameUrl', upFileUrlKey: 'url', upPosterUrlKey: 'frameUrl' }"
            :width="90"
            :height="160"
            :maxVideoSize="1024 * 10000"
            :accept="['.mp4', '.m4v', '.mov']"
            :limit="1"
          ></rest-upload-qn>
        </el-form-item>
        <el-form-item label="剧集海报" prop="episodeCover" required>
          <rest-upload-qn
            v-model="formData.episodeCover"
            :folder="`drama/${formData.dramaId || ''}/cover`"
            :accept="['.png', '.jpg', '.svg', '.webp']"
            :limit="1"
            :width="90"
            :height="160"
            :afterSelectFile="openCropper"
          ></rest-upload-qn>
        </el-form-item>
        <el-form-item label="" labelWidth="0px" style="margin-bottom: 0">
          <el-button type="primary" style="width: 100%" :disabled="submitLoading" :loading="submitLoading" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
      <rest-image-cropper ref="restImageCropperRef"></rest-image-cropper>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus';
  import { type DramaEpisode, editDamaEpisodeAxios } from '@/api/drama-management';
  type $Video = { frameUrl: string; episodeUrl: string };

  type $EditShowData = {
    dramaEpisode: DramaEpisode;
    /** 短剧名称 */
    dramaTitle: string;
    /** 编辑时的回调 */
    editCallBack: (dramaEpisode: DramaEpisode) => void;
  };
  let editCallBack: $EditShowData['editCallBack'] | undefined = undefined;
  const title = ref('');
  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const video: Ref<$Video | undefined> = ref();
  const restImageCropperRef: $RefComp<'RestImageCropper'> = ref(null);
  const submitLoading = ref(false);
  const formData: DramaEpisode = reactive<DramaEpisode>({
    dramaId: undefined,
    episodeId: undefined,
    episodeTitle: '',
    episodeCover: '',
    episodeUrl: '',
    frameUrl: '',
  });

  const rules = reactive<FormRules>({
    episodeTitle: [{ min: 3, max: 12, type: 'string', message: '短剧名称只能输入3-12个字符', trigger: ['blur', 'change'] }],
    episodeCover: [{ required: true, type: 'string', message: '请上传海报', trigger: ['change'] }],
    episodeUrl: [{ required: true, type: 'string', message: '请上传视频', trigger: ['change'] }],
  });

  watch(
    () => video.value,
    (val) => {
      if (val) {
        formData.episodeUrl = val.episodeUrl;
        formData.frameUrl = val.frameUrl;
        formData.episodeCover = formData.episodeCover || val.frameUrl;
      } else {
        formData.episodeUrl = '';
        formData.frameUrl = '';
      }
    }
  );

  /**
   * 显示
   */
  function show(data: $EditShowData) {
    title.value = `编辑剧集(${data.dramaTitle})`;
    formData.dramaId = data.dramaEpisode?.dramaId ? data.dramaEpisode.dramaId : undefined;
    formData.episodeId = data.dramaEpisode?.episodeId ? data.dramaEpisode.episodeId : undefined;
    formData.episodeTitle = data.dramaEpisode?.episodeTitle ? data.dramaEpisode.episodeTitle : '';
    formData.episodeCover = data.dramaEpisode?.episodeCover ? data.dramaEpisode.episodeCover : '';
    formData.episodeUrl = data.dramaEpisode?.episodeUrl ? data.dramaEpisode.episodeUrl : '';
    formData.frameUrl = data.dramaEpisode?.frameUrl ? data.dramaEpisode.frameUrl : '';
    editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;
    video.value = formData.episodeUrl ? { episodeUrl: formData.episodeUrl, frameUrl: formData.frameUrl || '' } : undefined;

    dialogVisible.value = true;
  }

  /** 打开裁剪框 */
  function openCropper(files: File[]): Promise<File[]> {
    return new Promise((resolve, reject) => {
      const file = files[0];
      if (file) {
        restImageCropperRef.value?.show({
          file,
          cropperOptions: { aspectRatio: 1080 / 1920, autoCropArea: 1 },
          croppedCanvasOptions: { minWidth: 720, maxWidth: 1080, maxHeight: 1920, minHeight: 1280 },
          fail: () => {
            reject(null);
          },
          success: (res: File) => {
            resolve([res] as File[]);
          },
        });
      } else {
        resolve(files);
      }
    });
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  /** 提交 */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      try {
        submitLoading.value = true;
        const res = await editDamaEpisodeAxios(formData);
        typeof editCallBack === 'function' && editCallBack(res.data);
        submitLoading.value = false;
        ElToast.success('提交成功');
        hide();
      } catch (error) {
        submitLoading.value = false;
        ElToast.error(error.msg || '提交失败，-BD003');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  defineExpose({ show, hide });
</script>
